package com.xijia.wuyouwallet.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.xijia.wuyouwallet.MyApp;
import com.xijia.wuyouwallet.R;
import com.xijia.wuyouwallet.adapter.BankListAdapter;
import com.xijia.wuyouwallet.api.MyCallBack;
import com.xijia.wuyouwallet.base.BaseActivity;
import com.xijia.wuyouwallet.bean.BankListData;
import com.xijia.wuyouwallet.utils.MyLogger;
import com.xijia.wuyouwallet.utils.UrlConfig;
import com.xijia.wuyouwallet.utils.XUtil;
import com.xijia.wuyouwallet.widget.ErrorHintView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * Created by Administrator on 2017/8/25 0025.
 */

public class BankCardActivity extends BaseActivity implements View.OnClickListener,BGARefreshLayout.BGARefreshLayoutDelegate{

    private ImageView bankCard_back;
    private BGARefreshLayout bankCard_reFresh;
    private ListView bankCard_lv;
    private ErrorHintView mErrorHintView;
    private LinearLayout bankCard_add_ll;

    private List<BankListData.DataBean.ListBean> list;
    private BankListAdapter adapter;

    //选择头像
    private PopupWindow bankPop;
    private RelativeLayout layout_rl_tilte;

    public static final int VIEW_CONTENT = 1;//view显示
    public static final int VIEW_WIFIFAILUER = 2;//显示断网
    public static final int VIEW_LOADFAILURE = 3;//加载失败
    public static final int VIEW_LOADING = 4;//加载
    public static final int VIEW_NODATA = 5;//无数据

    private String card_id;

    //新添加
    private TextView bankCard_saving_tv,bankCard_credit_tv;
    private View bankCard_saving_view,bankCard_credit_view;

    private String cardType = "1";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bankcard);
        initView();
    }

    private void initView(){
        bankCard_back = (ImageView) findViewById(R.id.bankCard_back);
        bankCard_back.setOnClickListener(this);
        bankCard_reFresh = (BGARefreshLayout) findViewById(R.id.bankCard_reFresh);
        bankCard_lv = (ListView) findViewById(R.id.bankCard_lv);
        mErrorHintView = (ErrorHintView) findViewById(R.id.mErrorHintView);
        bankCard_add_ll = (LinearLayout) findViewById(R.id.bankCard_add_ll);
        bankCard_add_ll.setOnClickListener(this);
        layout_rl_tilte = (RelativeLayout) findViewById(R.id.layout_rl_tilte);
        bankCard_saving_tv = (TextView) findViewById(R.id.bankCard_saving_tv);
        bankCard_saving_tv.setOnClickListener(this);
        bankCard_credit_tv = (TextView) findViewById(R.id.bankCard_credit_tv);
        bankCard_credit_tv.setOnClickListener(this);
        bankCard_saving_view = findViewById(R.id.bankCard_saving_view);
        bankCard_credit_view = findViewById(R.id.bankCard_credit_view);


        bankCard_reFresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApp.getInstance(), true));
        bankCard_reFresh.setDelegate(this);
        list = new ArrayList<>();
        adapter = new BankListAdapter(list,this);
        bankCard_lv.setAdapter(adapter);
        bankCard_lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                card_id = list.get(i).getCard_id();
                if (bankPop == null) {
                    initPop(i);
                }
                bankPop.showAtLocation(layout_rl_tilte, Gravity.TOP, 0, 0);
                return true;
            }
        });
        bankCard_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                /*if (MyApp.isBankFinsh){
                    MyApp.isBankFinsh = false;
                    Intent intent = new Intent();
                    intent.putExtra("img",list.get(i).getBank_logo());
                    intent.putExtra("name",list.get(i).getCard_bank());
                    intent.putExtra("num",list.get(i).getCard_number());
                    intent.putExtra("cardId",list.get(i).getCard_id());
                    intent.putExtra("cardType",list.get(i).getCard_type());
                    BankCardActivity.this.setResult(Constants.RESULT_DATA,intent);
                    BankCardActivity.this.finish();
                }else {
                    return;
                }*/
            }
        });
        showLoading(VIEW_LOADING);
        requestData(true,false,cardType);
    }

    //初始化改换头像popup
    private void initPop(final int postion) {
        View popView = View.inflate(this, R.layout.pop_bank_unbind, null);
        bankPop = new PopupWindow(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        TextView popup_bank_unbind_config = (TextView) popView.findViewById(R.id.popup_bank_unbind_config);
        TextView popup_bank_unbind_cancel = (TextView) popView.findViewById(R.id.popup_bank_unbind_cancel);
        RelativeLayout popup_bank_rl_all = (RelativeLayout) popView.findViewById(R.id.popup_bank_rl_all);
        popup_bank_rl_all.getBackground().setAlpha(150);
        popup_bank_rl_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bankPop.dismiss();
            }
        });
        popup_bank_unbind_config.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bankPop.dismiss();
                delectData(postion);
            }
        });
        popup_bank_unbind_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bankPop.dismiss();
            }
        });
        bankPop.setContentView(popView);
    }

    /**
     *清除状态
     */
    private void clearBottom(){
        bankCard_saving_tv.setTextColor(getResources().getColor(R.color.font2));
        bankCard_credit_tv.setTextColor(getResources().getColor(R.color.font2));
        bankCard_saving_view.setVisibility(View.GONE);
        bankCard_credit_view.setVisibility(View.GONE);
    }

    private void requestData(final boolean isFirst, final boolean isResh,String cardType){
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("type",cardType);
        XUtil.Post(UrlConfig.GET_BANKCARD_LIST,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                //MyLogger.wLog().e("获取银行卡列表result="+result);
                BankListData data = JSONObject.parseObject(result,BankListData.class);
                if (data.getCode()==200){
                    if (isFirst){
                        if (!list.isEmpty()){
                            list.clear();
                        }
                        showLoading(VIEW_CONTENT);
                    }
                    if (isResh){
                        if (!list.isEmpty()){
                            list.clear();
                        }
                        bankCard_reFresh.endRefreshing();
                    }
                    for (BankListData.DataBean.ListBean listBean : data.getData().getList()){
                        list.add(listBean);
                    }
                    adapter.notifyDataSetChanged();
                }else {
                    if (isResh){
                        bankCard_reFresh.endRefreshing();
                        if (list.isEmpty()){
                            showLoading(VIEW_NODATA);
                        }
                    }
                    if (isFirst){
                        showLoading(VIEW_NODATA);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                //MyLogger.wLog().e("获取银行卡列表onError="+ex.toString());
                if (isFirst){
                    showLoading(VIEW_LOADFAILURE);
                }
                if (isResh){
                    bankCard_reFresh.endRefreshing();
                }
            }
        });
    }

    /**
     *
     */
    private void delectData(final int postion){
        Map<String,Object> map = new HashMap<>();
        map.put("token",MyApp.userData.getData().getToken());
        map.put("user",MyApp.userData.getData().getUser_id());
        map.put("card_id",card_id);
        showProgressDialog(true);
        XUtil.Post(UrlConfig.UNBIND_BANCARD_URL,map,new MyCallBack<String>(){

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                dismissProgressDialog();
                //MyLogger.wLog().e("删除银行卡result"+result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (jsonObject.getInteger("code")==200){
                    showToast("解除成功");
                    list.remove(postion);
                    //bankCard_reFresh.beginRefreshing();
                    //requestData(false,true,cardType);
                    adapter.notifyDataSetChanged();
                    if (list.isEmpty()){
                        showLoading(VIEW_NODATA);
                    }
                }else {
                    showToast(jsonObject.getString("msg"));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                dismissProgressDialog();
                MyLogger.wLog().e("删除银行卡onError"+ex.toString());
            }
        });
    }

    //显示对话框
    private void showLoading(int i) {
        bankCard_reFresh.setVisibility(View.GONE);
        mErrorHintView.setVisibility(View.GONE);
        switch (i) {
            case VIEW_CONTENT:
                mErrorHintView.hideLoading();
                bankCard_reFresh.setVisibility(View.VISIBLE);
                break;
            case VIEW_WIFIFAILUER:
                mErrorHintView.hideLoading();
                mErrorHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        //requestBanner();
                        //requestList(true, false, false, false, itemStateId, orderId, cycle_id);
                    }
                });
                break;
            case VIEW_LOADFAILURE:
                mErrorHintView.hideLoading();
                mErrorHintView.loadFailure(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        showLoading(VIEW_LOADING);
                        requestData(true,false,cardType);
                    }
                });
                break;
            case VIEW_NODATA:
                mErrorHintView.hideLoading();
                mErrorHintView.noData(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {

                    }
                });
                break;
            case VIEW_LOADING:
                mErrorHintView.loadingData();
                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (MyApp.isCard){
            MyApp.isCard = false;
            MyApp.isChoiseCard = false;
            showLoading(VIEW_LOADING);
            requestData(true,false,cardType);
        }
    }

    @Override
    public void onClick(View view) {
        Bundle bundle = null;
        switch (view.getId()){
            case R.id.bankCard_back:
                finish();
                break;
            case R.id.bankCard_add_ll:
                bundle = new Bundle();
                bundle.putString("cardType",cardType);
                jumpToPage(AddBankcardActivity.class,bundle);
                break;
            case R.id.bankCard_saving_tv://储蓄卡
                clearBottom();
                bankCard_saving_tv.setTextColor(getResources().getColor(R.color.main_orange));
                bankCard_saving_view.setVisibility(View.VISIBLE);
                cardType = "1";
                showLoading(VIEW_LOADING);
                requestData(true,false,cardType);
                break;
            case R.id.bankCard_credit_tv://信用卡
                clearBottom();
                bankCard_credit_tv.setTextColor(getResources().getColor(R.color.main_orange));
                bankCard_credit_view.setVisibility(View.VISIBLE);
                cardType = "0";
                showLoading(VIEW_LOADING);
                requestData(true,false,cardType);
                break;
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        requestData(false,true,cardType);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }
}
